package com.chinasoftosg.sicap.scheduling.job;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

/**
 * 〈一句话功能简述〉 〈功能详细描述〉
 * 
 * @author [作者]（必须）
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （必须）
 * @2012-4-26
 */

public class ImportLoader {
	private String localFile = "D:/workspace/Sudan/123.log";

	private BillingDaoImp dao;
	
    /***
     * 日志文件
     */
    private Logger logger = Logger.getLogger(this.getClass());

	public ImportLoader() {
	}

	public ImportLoader(String localFile) {
		this.localFile = localFile;
	}

	public void excute(String localFile, ConfigLoader loader) {
	    logger.info("=====开始读取文件=====");
		this.localFile = localFile;
		try {
			readFile(loader);
		} catch (Exception e) {
		    logger.warn(""+e.getMessage());
		}
		logger.info("文件读取结束=====");
	}

	public void readFile(ConfigLoader loader) {
		try {
			System.out.println("read file ...." + localFile);
			FileInputStream fis = new FileInputStream(localFile);
			InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
			dao.setSql(loader.getInsertSql());
			BufferedReader br = new BufferedReader(isr);
			String line = "";
			String[] arrs = null;
			int len = loader.getSplitIndexs().length;
			String[] types = loader.getTypes();
			String[] values = null;
			int[] indexs = loader.getSplitIndexs();
			List<String[]> billings = new ArrayList<String[]>();

			int count = 0;
			while ((line = br.readLine()) != null) {
				arrs = line.split("\\" + loader.getRule());
				values = new String[len];

				for (int i = 0; i < len; i++) {

					if (indexs[i]> arrs.length) {
						values[i] = "";
					} else {
						values[i] = arrs[indexs[i] - 1];
					}
				}
				billings.add(values);
				count = count + 1;
				if (count % loader.getMaxCommitNumber() == 0) {
					dao.insert(billings, types);
					billings = new ArrayList<String[]>();
					System.out.println("insert1 调用 ");
				}
			}
			if (count % loader.getMaxCommitNumber() != 0) {
				dao.insert(billings, types);
				System.out.println("insert2 调用");
			}
			br.close();
			isr.close();
			fis.close();
		} catch (Exception e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
	}

	public void saveBilling() {

	}

	public String getLocalFile() {
		return localFile;
	}

	public void setLocalFile(String localFile) {
		this.localFile = localFile;
	}

	public BillingDaoImp getDao() {
		return dao;
	}

	public void setDao(BillingDaoImp dao) {
		this.dao = dao;
	}

    public Logger getLogger()
    {
        return logger;
    }

    public void setLogger(Logger logger)
    {
        this.logger = logger;
    }

}
